/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.model.core.*;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.ContentResourceManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.VirtualFolderForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.LinkedObjectsInfoContainer;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.struts.action.*;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>Moves content resource folder
 * </p>
 * <p><a href="MoveContentResourceFolderAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.1 $ $Date: 2007/12/18 18:11:46 $
 * @struts.action path="/core/contentResource/moveFolder"
 * name="virtualFolderForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentResource-update"
 * @struts.action-forward name="inputForward"
 * path=".core.contentResource.moveFolder"
 * @struts.action-forward name="listContentResources"
 * path="/core/contentResource/list.do"
 * redirect="true"
 * @struts.action-forward name="viewLinkedObjects"
 * path="/core/linkedObjects/view.do"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentResource/list.do"
 */
public final class MoveContentResourceFolderAction extends BaseAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        if ( isCancelled(request) ) {
            return mapping.findForward("listContentResources");
        }

        HttpSession session = request.getSession();

        // flag shows whether to force changing of URI if there're some
        // linked objects
        boolean force = "true".equalsIgnoreCase(request.getParameter("force"));

        VirtualFolderForm virtualFolderForm;
        if (force) {
            virtualFolderForm = (VirtualFolderForm) session.getAttribute(WebappConstants.VIRTUAL_FOLDER_FORM_KEY);
        } else {
            virtualFolderForm = (VirtualFolderForm) form;
        }
        String path = virtualFolderForm.getPath();
        String initialPath = path;

        if ( path == null || path.equals("/") ) {
			path = "";
		}

		// ensure, that current folder starts with slash and does not end with slash
		if ( path.length() > 0 ) {
			if ( !path.startsWith("/") ) {
				path = "/" + path;
			}
			if ( path.endsWith("/") ) {
				path = path.substring(0, path.length() - 1);
			}
		}

        String newPath = virtualFolderForm.getNewPath();
        if ( newPath == null || newPath.equals("/") ) {
			newPath = "";
		}

		// ensure, that new path starts with slash and does not end with slash
		if ( newPath.length() > 0 ) {
			if ( !newPath.startsWith("/") ) {
				newPath = "/" + newPath;
			}
			if ( newPath.endsWith("/") ) {
				newPath = newPath.substring(0, newPath.length() - 1);
			}
		}

        // get all content resources, which exist in given folder
        String whereClause = "r.uri like '" + StringUtil.sqlEscape(Constants.RESOURCES_URI_PREFIX + path + "/") + "%'";
        QueryInfo queryInfo = new QueryInfo();
		queryInfo.setWhereClause(whereClause);

        ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
        PartialCollection contentResources = contentResourceManager.listContentResources(queryInfo);

		if (contentResources.isEmpty()) {
			// content resources not found. they might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("virtualFolderIsEmpty", new ActionMessage("core.virtialFolder.errors.empty"));
			saveErrors(request, errors);
            return mapping.findForward("listContentResources");
		}

        // collecting IDs of used resources
        List usedResourcesIds = new ArrayList();
        for (Iterator i = contentResources.iterator(); i.hasNext(); ) {
            ContentResource contentResource = (ContentResource) i.next();
            if (contentResource.isInUse()) {
                usedResourcesIds.add(contentResource.getId());
            }
        }

        if (!force && !usedResourcesIds.isEmpty() ) {
            // trying to change URI of some used content resources - display warning
            String action = mapping.findForward("listContentResources").getPath();
            String redirectUrl = WebappUtil.getActionMappingURL(action, null, request, WebappConstants.URL_TYPE_DOMAIN_RELATIVE);
            session.setAttribute(WebappConstants.VIRTUAL_FOLDER_FORM_KEY, virtualFolderForm);
            ActionMessages messages = new ActionMessages();
            messages.add("changeUriWarning", new ActionMessage("core.contentResource.messages.folderChangeUriWarning"));
            saveMessages(request, messages);

            LinkedObjectsInfoContainer container = new LinkedObjectsInfoContainer();
            container.setRedirectUrl(redirectUrl);
            container.setPath(initialPath);
            container.setNewPath(virtualFolderForm.getNewPath());
            container.setUpdateAction(mapping.getPath());
            container.setObjectsIds(usedResourcesIds);
            container.setObjectType(LinkedObjectsInfoContainer.TYPE_RESOURCE);
            session.setAttribute(WebappConstants.LINKED_OBJECTS_INFO_CONTAINER_KEY, container);

            return mapping.findForward("viewLinkedObjects");
        }

        CacheUtil cacheUtil = CacheUtil.getInstance(request);
        SearchManager searchManager = SearchManager.getInstance(session.getServletContext());

        boolean someAlreadyExist = false;
        boolean someWereUpdated = false;

        for (Iterator resourcesIterator = contentResources.iterator(); resourcesIterator.hasNext(); ) {
            ContentResource contentResource = (ContentResource) resourcesIterator.next();

            //setup uri
            String uri = contentResource.getUri();
            String oldUri = uri;
            uri = uri.substring(Constants.RESOURCES_URI_PREFIX.length());
            uri = uri.substring(path.length());
            uri = newPath + uri;
            uri = Constants.RESOURCES_URI_PREFIX + uri;
            contentResource.setUri(uri);

            // remove links to this resource from unmodifiable menu items
            for (Iterator i = contentResource.getLinkedMenuItems().iterator(); i.hasNext();) {
                MenuItem menuItem = (MenuItem) i.next();
                if (!menuItem.isDynamic()) {
                    i.remove();
                }
            }

            try {
                contentResourceManager.updateContentResource(contentResource, contentResource.getResourceData());

                //flush cache
                cacheUtil.flushResourceCache(oldUri);

                //put into cache
                CacheUtil.ResourceData rd = new CacheUtil.ResourceData(contentResource.getResourceData().getData(), contentResource.getMimeType(), WebappUtil.rolesToString(contentResource.getRoles()), contentResource.getLastUpdatedDatetime().getTime());
                cacheUtil.putResourceInCache(rd, uri);

                //reindex
                if ( contentResource instanceof ContentDocument ) {
                    searchManager.unIndexDocument(oldUri, request);
                    searchManager.indexDocument((ContentDocument) contentResource, request);
                }

                if (force) {
                    // reindex and update cache for linked objects, because they
                    // were changed

                    // flush cache related to menu items
                    cacheUtil.flushMenuCache();

                    // put linked values in cache and into search index
                    List linkedContentFieldValues = contentResource.getLinkedContentFieldValues();
                    Set owners = new HashSet();
                    for (Iterator i = linkedContentFieldValues.iterator(); i.hasNext();)
                    {
                        ContentFieldValue fieldValue = (ContentFieldValue) i.next();
                        ContentField field = fieldValue.getContentField();
                        Localizable owner = field.getOwner();
                        // put owner to set of owners to cache/reindex them later
                        owners.add(owner);

                        String localeIdentifier = fieldValue.getContentLocale().getIdentifier();

                        byte fieldType = field.getType();
                        String content;

                        if (fieldType == ContentField.LINE_TYPE) {
                            content = fieldValue.getSimpleValue();
                        } else {
                            content = ConvertUtil.convertToString(fieldValue.getValue());
                        }
                        if (owner instanceof Page) {
                            Page page = (Page) owner;
                            CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId(), owner.getId());
                            cacheUtil.putPageFieldValueInCache(cfvData, page.getUri(), field.getIdentifier(), localeIdentifier);
                        }
                    }

                    // process owners
                    for (Iterator i = owners.iterator(); i.hasNext();) {
                        Localizable owner = (Localizable) i.next();
                        if (owner instanceof Layout) {
                            Layout layout = (Layout) owner;
                            cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());

                            //TODO: add into search index for every content page of the layout.
                            //TODO: add into index action pages
                            List contentPages = layout.getContentPages();
                            for (int j = 0; j < contentPages.size(); j++) {
                                ContentPage cp = (ContentPage) contentPages.get(j);
                                searchManager.reIndexPage(cp, request);
                                cacheUtil.updateContentPageLastModifiedInCache(cp.getUri());
                            }

                        } else if (owner instanceof Page) {
                            Page page = (Page) owner;
                            searchManager.reIndexPage(page, request);
                            if (page instanceof ContentPage) {
                                cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
                            }
                        }
                    }
                }

            } catch (BeanAlreadyExistsException e) {
                // some resource already exists
                someAlreadyExist = true;
            } catch (ObjectOptimisticLockingFailureException e) {
                // some resource was updated or deleted by another transaction
                someWereUpdated = true;
            }
        }

        ActionMessages errors = new ActionMessages();
        if (someAlreadyExist) {
            // some resource already exists
            errors.add("someContentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.someAlreadyExists"));
        }
        if (someWereUpdated) {
            // some resource was updated or deleted by another transaction
            errors.add("someUpdateFailed", new ActionMessage("core.contentResource.errors.someUpdateFailed"));
        }
        if (someAlreadyExist || someWereUpdated) {
            saveErrors(request, errors);
        }

        return mapping.findForward("listContentResources");
    }
}